import requests
import chardet


def test1():
    r = requests.get("https://www.baidu.com")
    print(type(r))
    print(r.status_code)
    print(r.cookies)
    r.encoding = "utf-8"
    print(r.text)


# 请求地址带参数
def test2():
    data = {"key1": "value1", "key2": "value2"}
    r = requests.get("url", params=data)
    # get请求会自动在后面拼接?,&符号信息


# 修改获取内容的编码
def chardet_test():
    r = requests.get("https://www.baidu.com")
    print(chardet.detect(r.content))
    # 将获取到的内容的编码格式，重新赋值
    r.encoding = chardet.detect(r.content)['encoding']
    print(r.text)


# requests 设置请求头
def header_test():
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"}
    r = requests.get("https://www.baidu.com", headers=header)
    print(r.status_code)


# cookie测试
def cookie_demo():
    header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"}
    # 查看cookie
    r = requests.get("https://www.baidu.com", headers=header)
    for i in r.cookies.keys():
        print("key = {%s} value = {%s}" % (i, r.cookies.get(i)))
    # 携带自定义cookie
    cookie = dict(name="tom", age="18")
    r = requests.get("https://www.baidu.com", headers=header, cookies=cookie)


# 使用session处理cookie
def session_cookie():
    loginUrl = ""
    s = requests.session()
    # 使用session请求一次，使后台创建一个cookie。比如页面登录时需要获取cookie信息
    r = s.get(loginUrl, allow_redirects=True)
    datas = {'name': 'name', 'password': 'password'}
    # 使用返回的cookie，提交新的数据
    r = s.post(loginUrl, data=datas, allow_redirects=True)
